package com.example.tangyee.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.tangyee.R;
import com.example.tangyee.bean.Question;
import com.example.tangyee.fragment.QuestionFragmentForViewPager;
import com.example.tangyee.utils.ConstantsUtil;
import com.lxj.xpopup.XPopup;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PredictActivity extends AppCompatActivity {

    private static final String TAG = "PredictActivity";

    private Unbinder mUnbinder;

    @BindView(R.id.back)
    View back;

    @BindView(R.id.root_view)
    View rootView;

    @BindView(R.id.tabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;

    @BindView(R.id.last)
    TextView last;
    @BindView(R.id.next)
    TextView next;

    @BindView(R.id.loading_view)
    View loadView;

    List<Fragment> fragments = new ArrayList<>();
    List<String> titles = new ArrayList<>();

    public List<Question> data = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_predict);
        mUnbinder = ButterKnife.bind(this);

        new GetQuestions().execute();
    }

    @OnClick(R.id.next)
    public void selectNextTab() {
        int pos = mTabLayout.getSelectedTabPosition();
        if (pos < data.size() - 1) {
            mTabLayout.getTabAt(pos + 1).select();
            next.setText("下一题");
        } else {
            next.setText("提交");
        }
    }

    @OnClick(R.id.last)
    public void selectLastTab() {
        int pos = mTabLayout.getSelectedTabPosition();
        if (pos > 0) {
            mTabLayout.getTabAt(pos - 1).select();
        }
    }

    public void checkScore() {
        int score = 0;
        for (int i = 0; i < data.size(); i ++) {
            Question question = data.get(i);
            if (question.getScore() < 0) {
                Snackbar.make(rootView, "还有问题未填写答案。", Snackbar.LENGTH_SHORT).show();
                mTabLayout.getTabAt(i).select();
                return;
            }
            score += question.getScore();
        }
        if (score >= 5) {
            XPopup.get(this).asConfirm("风险评估", "风险指数大于5，您患2型糖尿病的风险很大.", null).show();
        } else if (score >= 3) {
            XPopup.get(this).asConfirm("风险评估", "您患2型糖尿病的风险为中度.", null).show();
        } else {
            XPopup.get(this).asConfirm("风险评估", "您患2型糖尿病的风险较低.", null).show();
        }
    }

    private class GetQuestions extends AsyncTask<Void, Void, List<Question>> {

        @Override
        protected List<Question> doInBackground(Void... voids) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .retryOnConnectionFailure(false)
                    .build();

            Request request = new Request.Builder()
                    .url(ConstantsUtil.GET_QUESTIONS)
                    .build();

            String respStr = null;
            try {
                Response response = okHttpClient.newCall(request).execute();
                if (response == null) {
                    return null;
                }
                respStr = response.body().string();
                if (respStr == null) {
                    return null;
                }
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
            }
            List<Question> questions = new ArrayList<>();

            try {
                respStr = respStr.substring(29, respStr.length()-2).trim();
                Log.d(TAG, "doInBackground: " + respStr);
                JSONArray jsonArray = new JSONArray(respStr);
                // 将json转成list
                parseItems(questions, jsonArray);
            } catch (JSONException je) {
                Log.e(TAG, "Failed to parse JSON", je);
            }  catch (NullPointerException npe) {
                Log.e(TAG, "doInBackground: ", npe);
                return null;
            }

            return questions;
        }

        @Override
        protected void onPostExecute(List<Question> questions) {
            if (questions == null) {
                ProgressBar progressBar = rootView.findViewById(R.id.progressBar);
                progressBar.setVisibility(View.GONE);
                TextView textView = rootView.findViewById(R.id.loading);
                textView.setText("请求超时···");
            } else if (questions.size() == 0) {
                ProgressBar progressBar = rootView.findViewById(R.id.progressBar);
                progressBar.setVisibility(View.GONE);
                TextView textView = rootView.findViewById(R.id.loading);
                textView.setText("未能获取到数据···");
            } else {
                data = questions;

                initTabView();
                loadView.setVisibility(View.GONE);

                View  view = rootView.findViewById(R.id.container);
                view.setVisibility(View.VISIBLE);

                AlphaAnimation aa = new AlphaAnimation(0, 1);
                aa.setDuration(1000);
                view.startAnimation(aa);
            }
        }
    }

    private void initTabView() {
        // 初始化标题与Fragments
        for (int i = 1; i <= data.size(); i ++) {
            titles.add("第"+i+"题");
            fragments.add(QuestionFragmentForViewPager.newInstance(this, i-1));
        }

        // 初始化ViewPager，并设置Adapter
        mViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return fragments.get(i);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == data.size()-1) {
                    next.setText("提交");
                } else if (!"下一题".equals(next.getText().toString())) {
                    next.setText("下一题");
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        mViewPager.setOffscreenPageLimit(data.size()-1);
        // 将 TabLayout 与 ViewPager 关联起来
        mTabLayout.setupWithViewPager(mViewPager);

        next.setOnClickListener(v -> {
            if ("提交".equals(next.getText().toString())) {
                checkScore();
            } else {
                selectNextTab();
            }
        });
    }

    private void parseItems(List<Question> questions, JSONArray jsonArray) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i ++) {
            Question question = new Question();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            question.setQuestionId(jsonObject.getString("questionId"));
            question.setQuestionTitle(jsonObject.getString("questionTitle"));
            JSONArray ja = jsonObject.getJSONArray("answerItems");
            Map<String, Integer> map = new LinkedHashMap<>();
            for (int j = 0; j < ja.length(); j ++) {
                jsonObject = ja.getJSONObject(j);
                map.put(jsonObject.getString("answer"), jsonObject.getInt("score"));
                Log.d(TAG, "parseItems: " + map.toString());
            }
            question.setAnswerItems(map);
            questions.add(question);
        }
    }

    @OnClick(R.id.back)
    public void back() {
        onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}
